/**
 * 
 */
package combobox;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

/**
 * @author Ken
 *
 */
public class IconComboboxRenderer extends JLabel implements ListCellRenderer{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final int OFFSET = 16;
    protected Color m_textSelectionColor = Color.WHITE;
    protected Color m_textNonSelectionColor = Color.BLACK;
    protected Color m_bkSelectionColor = Color.BLUE;
    protected Color m_bkNonSelectionColor = Color.WHITE;
    
    protected Color m_textColor;
    protected Color m_bkColor;
    protected boolean m_hasFocus;
    protected List<Border> m_borders;	
	
    public IconComboboxRenderer() {
    	super();
        m_textColor = m_textNonSelectionColor;
        m_bkColor = m_bkNonSelectionColor;
        m_borders = new ArrayList<Border>();
        setOpaque(false);
	}
    
	@Override
	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
        if (value == null)
            return this;
        setText(value.toString());
        if (value instanceof ListboxItem){
        	ListboxItem ldata = (ListboxItem)value;                       
            setIcon(ldata.getIcon());
            int ind = 0;
            if (index >= 0)
                ind = ldata.getIndex();
            Border b = (ind < m_borders.size() ? m_borders.get(ind) : new EmptyBorder(OFFSET * ind, 0, 0, 0));
            setBorder(b);            
        }
        else{
            setIcon(null);
        }
        setFont(list.getFont());
        m_textColor = isSelected ? m_textSelectionColor : m_textNonSelectionColor;
        m_bkColor = isSelected ? m_bkSelectionColor : m_bkNonSelectionColor;
        m_hasFocus = cellHasFocus;
        return this;
	}
	
	@Override
	public void paint(Graphics g) {
		Icon icon = getIcon();
        g.setColor(m_bkNonSelectionColor);
        g.fillRect(0, 0, getWidth(), getHeight());
        
        g.setColor(m_bkColor);
        int offset = 0;
        if (icon != null && getText() != null){
            Insets ins = getInsets();
            offset = ins.left + icon.getIconWidth() + getIconTextGap();            
        }
        g.fillRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1);
        if (m_hasFocus)
        {
            g.setColor(m_bkSelectionColor);
            g.drawRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1);            
        }
        setForeground(m_textColor);
        setBackground(m_bkColor);
        super.paint(g);
	}
}
